<script setup lang="tsx">
import { ElButton, ElInput } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'

import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ref, reactive, unref, computed } from 'vue'
import { ElSwitch, ElMessage, ElDatePicker } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { getAddUserListApi, getPartnerInfoApi } from '@/api/earnings'
import { getAllUserApi, banUserApi } from '@/api/user'
import { useUserStore } from '@/store/modules/user'
import ProportionDialog from './components/ProportionDialog.vue'
import EarningsDialog from './components/EarningsDialog.vue'
import { onMounted } from 'vue'
const userStore = useUserStore()
const { t } = useI18n()

const earningsInfo = ref<any>({})
const getEarnings = async (searchFormData) => {
  if (userStore.getUserInfo.roleId != 1) {
    const { data } = await getPartnerInfoApi({
      appId: userStore.getAppId,
      ...searchFormData
    })
    earningsInfo.value = data
  } else {
    const { data } = await getAddUserListApi({
      appId: userStore.getAppId,
      ...searchFormData
    })
    earningsInfo.value = data
  }
  //
}

onMounted(() => {
  getEarnings(null)
})

//formSchema
const { searchRegister, searchMethods } = useSearch()
const { getFormData: getSearchFormData, setValues: setSearchFormData } = searchMethods

const schema = computed<FormSchema[]>(() => [
  {
    field: 'Time',
    label: '日期筛选',
    component: 'DatePicker',
    formItemProps: {
      slots: {
        default: (formData) => {
          const times = computed({
            get: () => {
              if (formData.startDate && formData.endDate) {
                return [formData.startDate, formData.endDate]
              } else {
                return []
              }
            },
            set: (times) => {
              if (times) {
                formData.startDate = times[0]
                formData.endDate = times[1]
              } else {
                formData.startDate = undefined
                formData.endDate = undefined
              }
            }
          })
          return (
            <ElDatePicker
              v-model={times.value}
              type="daterange"
              valueFormat="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择日期范围"
            />
          )
        }
      }
    }
  },
  {
    field: 'code',
    label: '用户ID',
    component: 'Input',
    formItemProps: {
      slots: {
        default: (formData) => {
          return <ElInput v-model={formData.code}></ElInput>
        }
      }
    }
  },
  {
    field: 'partnerLevel',
    label: '合伙人级别',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '一级',
          value: '1'
        },
        {
          label: '二级',
          value: '2'
        },
        {
          label: '三级',
          value: '3'
        }
      ]
    },
    hidden: userStore.getUserInfo.roleId == 1
  }
])
const handleSearch = async () => {
  const searchFormData = await getSearchFormData()
  getEarnings(searchFormData)
  getList()
}
const handleReset = () => {
  setSearchFormData({
    startDate: undefined,
    endDate: undefined,
    code: undefined,
    partnerLevel: undefined
  })
  getEarnings(null)
  getList()
}
//Table
const { tableRegister, tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const searchFormData = await getSearchFormData()
    const { data, count } = await getAllUserApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      ...searchFormData
    })
    return {
      list: data,
      total: count
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
const isShow = ref(false)
const curItemIndex = ref(1)
const proportionDialogRef = ref()
const earningsDialogRef = ref()

const isShowUserName = (row: any) => {
  curItemIndex.value = row.id
  isShow.value = true
  setTimeout(() => {
    isShow.value = false
  }, 30000)
}
const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'createTime',
    label: '日期'
  },
  {
    field: 'userName',
    label: '用户名称'
  },
  {
    field: 'code',
    label: '用户ID',
    slots: {
      default: ({ row }) => {
        return (
          <div>
            {curItemIndex.value === row.id && isShow.value ? (
              row.code
            ) : (
              <span style={'color:blue'} onClick={() => isShowUserName(row)}>
                点击查看
              </span>
            )}
          </div>
        )
      }
    }
  },
  {
    field: 'pname',
    label: '所属合伙人'
  },
  {
    field: 'totalGoldNum',
    label: '总广告收益'
  },
  {
    field: 'loginIp',
    label: 'IP地址'
  },
  {
    field: 'loginTime',
    label: '最近登录'
  },
  {
    field: 'status',
    label: '启用/禁用',
    slots: {
      default: ({ row }: any) => {
        return (
          <ElSwitch
            v-model={row.status}
            activeValue={1}
            inactiveValue={0}
            onChange={(val: boolean) => {
              banUserApi({
                id: row.id,
                status: val ? 1 : 0
              }).then(() => {
                getList()
                ElMessage.success('操作成功')
              })
            }}
          ></ElSwitch>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 210,
    slots: {
      default: ({ row }) => {
        return (
          <div class="flex gap-1">
            <ElButton
              type="primary"
              size="small"
              onClick={() => proportionDialogRef.value.openDialog(row)}
            >
              {{
                default: () => '分成记录'
              }}
            </ElButton>
            <ElButton
              type="primary"
              size="small"
              onClick={() => earningsDialogRef.value.openDialog(row)}
            >
              {{
                default: () => '收益记录'
              }}
            </ElButton>
          </div>
        )
      }
    }
  }
])
</script>

<template>
  <ContentWrap title="实际收益">
    <Search
      :schema="schema"
      @register="searchRegister"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="flex w-[100%]">
      <div
        v-if="userStore.getUserInfo.roleId === 1"
        class="h-[50px] grow m-10px bg-#FAB800 flex items-center justify-center rounded-10px"
      >
        <span>实际收益:{{ earningsInfo.actualAmount ?? '0' }}</span>
      </div>
      <div class="h-[50px] grow m-10px bg-#FAB800 flex items-center justify-center rounded-10px">
        <span>合伙人收益:{{ earningsInfo.proxyAmount ?? '0' }}</span>
      </div>
      <div
        v-if="userStore.getUserInfo.roleId === 1"
        class="h-[50px] grow m-10px bg-#FAB800 flex items-center justify-center rounded-10px"
      >
        <span>总广告收益:{{ earningsInfo.totalAmount ?? '0' }}</span>
      </div>
      <div class="h-[50px] grow m-10px bg-#FAB800 flex items-center justify-center rounded-10px">
        <span
          >用户总收益:{{
            userStore.getUserInfo.roleId === 1
              ? (earningsInfo.todayIncomeTotal ?? '0')
              : (earningsInfo.todayAmount ?? '0')
          }}</span
        >
      </div>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      headerAlign="center"
      align="center"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
    <ProportionDialog ref="proportionDialogRef" />
    <EarningsDialog ref="earningsDialogRef" />
  </ContentWrap>
</template>
